<template>
  <div class="metal-health pad">
    <div class="head">
      <span>心理健康测评表管理</span>
      <!-- <el-button type="primary" circle icon="el-icon-plus" @click="openAddDialog"></el-button> -->
    </div>
    <div class="search m-t-b" v-if="name !== '3'">
      <el-input :placeholder="'搜索' + placeText" @input="clearSearch"  v-model="searchTxt" clearable />
      <el-button type="primary" @click="handleSearch">
        <i class="el-icon-search"></i> 搜索
      </el-button>
    </div>

    <el-tabs type="border-card" class="m-t-b" @tab-click="handleClick">
      <el-tab-pane label="当前版本(正在使用)" name="0">
        <div class="chart-head">
          <el-button type="primary" @click="openAddDialog">添加心理测试表</el-button>
          <el-radio-group v-model="filterType" @change="changeChartType">
            <el-radio-button :label="'全部(' + curMentalList.length + ')'"></el-radio-button>
            <el-radio-button
              v-for="(item, i) in types"
              :key="i"
              :value="item.value"
              :label="item.label + '(' + item.total + ')'"
            ></el-radio-button>
          </el-radio-group>
        </div>
        <el-table class="m-t-b" stripe border :data="pageMentalList" v-loading="loading">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="简介(测试表描述)">
                  <span>{{props.row.psychologicalDesc || '暂无描述'}}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="表名" prop="psychologyTitle"></el-table-column>
          <el-table-column label="所属类型">
            <template slot-scope="scope">
              {{scope.row.categoryName || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="创建人">
            <template slot-scope="scope">
              {{scope.row.psychologyName || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="价格">
            <template slot-scope="scope">
              {{scope.row.price ? scope.row.price + '元' : '暂无'}}
            </template>
          </el-table-column>
          <!-- <el-table-column label="简介">
            <template slot-scope="scope">
              <p v-html="scope.row.psychologicalDesc"></p>
            </template>
          </el-table-column> -->
          <el-table-column label="性别要求">
            <template slot-scope="scope">
              {{sexFilter(scope.row.sex)}}
            </template>
          </el-table-column>
          <el-table-column label="年龄要求">
            <template slot-scope="scope">
              {{scope.row.minage}}岁 - {{scope.row.maxage}}岁
            </template>
          </el-table-column>
          <el-table-column label="测试类型">
            <template slot-scope="scope">
              {{scope.row.type | formatType}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="是否启用" fixed="right" width="150">
            <template slot-scope="scope">
              <el-switch
                active-text="启用"
                inactive-text="禁用"
                v-model="scope.row.isEnable"
                @change="confirmChange($event, scope.row, '测试表')"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="160px">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="seeDetail(scope.row)">查看</el-button>
              <el-button type="text" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button type="text" size="mini" @click="delMental(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleMentalPagi"
          :current-page="curMentalPage"
          :total="mentalTotal">
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="心理评测规则设置" name="1">
        <el-button type="primary" @click="openRuleDialog">添加规则</el-button>
        <el-table :data="mentalRules" border stripe class="m-t-b" v-loading="ruleLoading">
          <el-table-column label="规则名称" prop="title"></el-table-column>
          <el-table-column label="规则所属心理表" prop="psychologyTitle"></el-table-column>
          <el-table-column label="规则计算方式">
            <template slot-scope="scope">
              {{typeFilter(scope.row.type)}}
            </template>
          </el-table-column>
          <el-table-column label="规则对应题目" prop="rulesValue"></el-table-column>
          <el-table-column label="是否启用" fixed="right" width="150">
            <template slot-scope="scope">
              <el-switch
                active-text="启用"
                inactive-text="禁用"
                v-model="scope.row.isEnable"
                @change="confirmChange($event, scope.row, '心理规则')"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="150">
            <template slot-scope="scope">
              <el-button type="default" circle icon="el-icon-edit" @click="openRuleEdit(scope.row)"></el-button>
              <el-button type="danger" circle icon="el-icon-delete" @click="deleteRule(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handlePagi"
          :current-page="curRulePage"
          :total="ruleTotal">
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="心理评测答案设置" name="2">
        <el-button type="primary" @click="openAnswerAddDialog">添加答案设置</el-button>
        <el-table :data="mentalAnswerList" stripe border class="m-t-b" v-loading="answerLoading">
          <el-table-column type="expand" fixed>
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="结果评语">
                  <span>{{props.row.rulesValue || '暂无评语'}}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="关联心理健康表" prop="psychologyTitle"></el-table-column>
          <el-table-column label="关联心理规则" prop="title"></el-table-column>
          <el-table-column label="关联关键字" prop="keywordTitle"></el-table-column>
          <el-table-column label="性别">
            <template slot-scope="scope">
              {{scope.row.sex === '1' ? '男' : (scope.row.sex === '2' ? '女' : '无性别')}}
            </template>
          </el-table-column>
          <el-table-column label="年龄区间">
            <template slot-scope="scope">
              {{scope.row.minage}}岁 - {{scope.row.maxage}}岁
            </template>
          </el-table-column>
          <el-table-column label="评分区间">
            <template slot-scope="scope">
              {{scope.row.mins}}分 - {{scope.row.maxs}}分
            </template>
          </el-table-column>
          <el-table-column label="对应程度">
            <template slot-scope="scope">
              {{scope.row.degree || '暂无'}}
            </template>
          </el-table-column>
          <!-- <el-table-column label="结果评语">
            <template slot-scope="scope">
              {{scope.row.rulesValue ? scope.row.rulesValue : '暂无'}}
            </template>
          </el-table-column> -->
          <el-table-column label="是否正常">
            <template slot-scope="scope">
              {{scope.row.type === '1' ? '是' : '否'}}
            </template>
          </el-table-column>
          <el-table-column label="是否启用" fixed="right" width="150">
            <template slot-scope="scope">
              <el-switch
                active-text="启用"
                inactive-text="禁用"
                v-model="scope.row.isEnable"
                @change="confirmChange($event, scope.row, '心理答案')"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <template slot-scope="scope">
              <el-button type="default" circle icon="el-icon-edit" @click="openAnswerEdit(scope.row)"></el-button>
              <el-button type="danger" circle icon="el-icon-delete" @click="deleteAnswer(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleAnswerPagi"
          :current-page="curAnswerPage"
          :total="answerTotal">
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="心理类目设置" name="3">
        <el-button type="primary" @click="openAddCategoryDialog">添加心理类目</el-button>
        <el-table :data="mentalCategoryList" stripe border>
          <el-table-column label="类目名称" prop="categoryName"></el-table-column>
          <el-table-column label="用途">
            <template slot-scope="scope">
              {{categoryTypes[scope.row.categoryType]}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button circle icon="el-icon-edit" @click="openEditCategory(scope.row)"></el-button>
              <el-button type="danger" circle icon="el-icon-delete" @click="deleteCategory(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleCategoryPagi"
          :total="mentalCategoryTotal">
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="dialogTitle" :visible.sync="showDialog">
      <el-form :model="mentalForm" label-position="top" :rules="rules" ref="mental">
        <el-form-item label="表名" prop="psychologyTitle">
          <el-input v-model="mentalForm.psychologyTitle" />
        </el-form-item>
        <el-form-item label="所属类别" prop="categoryId">
          <el-select v-model="mentalForm.categoryId">
            <el-option v-for="(item, i) in allMentalCategory" :key="i" :label="item.categoryName" :value="item.categoryId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建人名称" prop="psychologyName">
          <el-input v-model="mentalForm.psychologyName" />
        </el-form-item>
        <el-form-item label="价格(选填)" prop="price">
          <el-input v-model="mentalForm.price" type="number" />
        </el-form-item>
        <el-form-item label="用途" prop="type">
          <el-select v-model="mentalForm.type">
            <el-option v-for="(item, i) in types" :key="i" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="psychologicalDesc">
          <el-input type="textarea" rows="8" v-model="mentalForm.psychologicalDesc" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="mentalForm.sex">
            <el-option :value="1" label="男"></el-option>
            <el-option :value="2" label="女"></el-option>
            <el-option :value="3" label="无性别限制"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄区间" prop="ageRange">
          <el-slider
            v-model="mentalForm.ageRange"
            range
            :max="100"
            :marks="marks"
            @change="changeRange"
            class="age-slider"
          >
          </el-slider>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary" @click="addMentalChart('mental')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showRuleDialog" :title="ruleDialogTitle">
      <el-form :model="ruleForm" ref="rule" label-position="top" :rules="rules">
        <el-form-item label="性别" prop="ruleSex">
          <el-select @change="changeRuleSex" v-model="ruleForm.ruleSex">
            <el-option :value="1" label="男"></el-option>
            <el-option :value="2" label="女"></el-option>
            <el-option :value="3" label="无性别限制"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则对应心理表" prop="psychologyTitleId">
          <el-select v-model="ruleForm.psychologyTitleId" @change="changeQuestion">
            <el-option v-for="(item, i) in fitMentalList" :key="i" :value="item.psychologyTitleId" :label="item.psychologyTitle"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则名称" prop="title">
          <el-input v-model="ruleForm.title" />
        </el-form-item>
        <el-form-item label="规则相关问题" prop="rulesValue">
          <el-select v-model="ruleForm.rulesValue" multiple filterable>
            <el-option v-for="(item, i) in usefulQuestion" :key="i" :label="item.title" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则计算方式" prop="type">
          <el-select v-model="ruleForm.type">
            <el-option label="除" :value="0"></el-option>
            <el-option label="乘" :value="1"></el-option>
            <el-option label="和" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideRuleDialog">取 消</el-button>
        <el-button :disabled="isDoing" type="primary" @click="addRule('rule')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="answerDialogTitle" :visible.sync="showAnswerDialog">
      <el-form :model="mentalAnswer" ref="answer" :rules="rules" label-position="top">
        <el-form-item label="性别" prop="sex">
          <el-select v-model="mentalAnswer.sex" @change="changeGender">
            <el-option :value="1" label="男"></el-option>
            <el-option :value="2" label="女"></el-option>
            <el-option :value="3" label="无性别限制"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联心理测试表" prop="psychologyTitleId">
          <el-select v-model="mentalAnswer.psychologyTitleId" @change="chartChange">
            <el-option v-for="item in answerChartList" :key="item.psychologyTitleId" :value="item.psychologyTitleId" :label="item.psychologyTitle"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联知识关键字(用于推荐知识)" prop="keywordId">
          <el-select v-model="mentalAnswer.keywordId" filterable @change="changeKeyword">
            <el-option
              v-for="item in keywordList"
              :key="item.keywordId"
              :label="item.keywordTitle"
              :value="item.keywordId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联心理规则设置" prop="psychologicalrulesId">
          <el-select v-model="mentalAnswer.psychologicalrulesId">
            <el-option v-for="item in answerRuleList" :key="item.id" :value="item.id" :label="item.title"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最小年龄" prop="minage">
          <el-input v-model="mentalAnswer.minage"/>
        </el-form-item>
        <el-form-item label="最大年龄" prop="maxage">
          <el-input v-model="mentalAnswer.maxage"/>
        </el-form-item>
        <el-form-item label="最小分数" prop="mins">
          <el-input v-model="mentalAnswer.mins" type="number" />
        </el-form-item>
        <el-form-item label="最大分数" prop="maxs">
          <el-input v-model="mentalAnswer.maxs" type="number" />
        </el-form-item>
        <el-form-item label="对应程度" prop="degree">
          <el-input v-model="mentalAnswer.degree" maxlength="3" />
        </el-form-item>
        <el-form-item label="结果评语">
          <el-input v-model="mentalAnswer.rulesValue" rows="8" type="textarea" />
        </el-form-item>
        <el-form-item label="是否正常" prop="type">
          <el-select v-model="mentalAnswer.type">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="异常" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生查看测评结果时, 是否隐藏规则程度">
          <el-radio-group v-model="mentalAnswer.fractionType">
            <el-radio :label="2">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideAnswerDialog">取 消</el-button>
        <el-button :disabled="canUse" type="primary" @click="addAnswer('answer')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="mentalCategoryDialogTitle" :visible.sync="showMentalCategory">
      <el-form :model="mentalCategory" label-position="top" ref="mentalCategory" :rules="rules">
        <el-form-item label="类目名称" prop="categoryName">
          <el-input v-model="mentalCategory.categoryName"></el-input>
        </el-form-item>
        <el-form-item label="用途">
          <el-radio-group v-model="mentalCategory.categoryType">
            <el-radio
              v-for="(item, index) in categoryTypes"
              :key="index"
              :label="index"
            >{{item}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideCategoryDialog">取 消</el-button>
        <el-button :disabled="canUse" type="primary" @click="addCategory('mentalCategory')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addMental,
  editMental,
  deleteMentalChart,
  getAllMentalChart,
  addMentalRule,
  getMentalRuleList,
  updateMentalRule,
  deleteMentalRule,
  getAllMentalQuestion,
  getAllMentalRule,
  getMentalAnswer,
  addMentalAnswer,
  updateMentalAnswer,
  deleteMentalAnswer,
  getQuestionListByMentalId,
  addMentalCategory,
  updateMentalCategory,
  deleteMentalCategory,
  getMentalCategoryByPage,
  getAllMentalCategory,
  getMentalChartByPage
} from '../api';
import {
  getAllKeyWords
} from '../api/version2.js';
import { formatDate } from '../util/index';

export default {
  name: 'MentalHealth',
  data () {
    const validateRange = (rules, value, callback) => {
      if (value[0] === value[1]) {
        return callback(new Error('年龄区间选择错误'))
      };
      callback()
    };
    const validateScore = (rules, value, callback) => {
      if (value[0] === value[1]) {
        return callback(new Error('分数区间选择错误'))
      };
      callback()
    };
    const validateMax = (rules, value, callback) => {
      if (value != '0' && !value) {
        return callback(new Error('最大分数不能为空'))
      };
      if (Number(value) <= Number(this.ruleForm.min)) {
        return callback(new Error('最大分数必须大于最小分数'))
      };
      callback()
    };
    const validateAnswerMax = (rules, value, callback) => {
      if (value != '0' && !value) {
        return callback(new Error('最大分数不能为空'))
      };
      if (Number(value) <= Number(this.mentalAnswer.mins)) {
        return callback(new Error('最大分数必须大于最小分数'))
      };
      callback()
    };
    const validateAge = (rules, value, callback) => {
      if (value != '0' && !value) {
        return callback(new Error('最大年龄不能为空'))
      };
      if (Number(value) <= Number(this.mentalAnswer.minage)) {
        return callback(new Error('最大年龄必须大于最小年龄'))
      };
      callback()
    };
    return {
      placeText: '心理测试表',
      name: '0',
      curMentalPage: 1,
      searchTxt: '',
      filterType: '',
      answerChartList: [],
      mentalList: [],
      total: 0,
      dialogTitle: '添加心理健康测试',
      loading: true,
      showDialog: false,
      showRuleDialog: false,
      canUse: false,
      ruleDialogTitle: '添加心理评测规则',
      showAnswerDialog: false,
      answerLoading: true,
      answerDialogTitle: '添加心理测评答案设置',
      pageSize: 10,
      ruleTotal: 0,
      curRuleId: '',
      usefulChart: [],
      fitMentalList: [],
      curMentalList: [],
      oldMentalList: [],
      questions: [],
      usefulQuestion: [],
      keywordList: [],
      mentalRules: [],
      ruleLoading: true,
      mentalTotal: 0,
      isDoing: false,
      answerTotal: 0,
      metalRules: [],
      answerRuleList : [],
      mentalAnswerList: [],
      curAnswerId: '',
      editorConfig: {}, // 富文本编辑器配置
      curRulePage: 0,
      curAnswerPage: 0,
      allMentalCategory: [],
      mentalAnswer: {
        psychologyTitleId: '', // 标题id
        psychologicalrulesId: '', // 规则id
        keywordId: '',
        keywordTitle: '',
        mins: '',
        maxs: '',
        rulesValue: '',
        type: '',
        minage: '',
        maxage: '',
        sex: '',
        enable: 1,
        degree: '',
        fractionType: 1,
      },
      types: [
        { label: '自测', value: 0, total: 0 },
        { label: '他测', value: 1, total: 0 },
        { label: '初筛表', value: 2, total: 0 },
        { label: '基础量表', value: 3, total: 0 },
        { label: '医生帮测量表', value: 6, total: 0 }
      ],
      categoryTypes: [
        '知心意', '健康尺', '消防', '公用'
      ],
      mentalForm: {
        psychologyTitle: '',
        psychologicalDesc: '',
        type: '',
        ageRange: [3, 25],
        sex: '',
        ruleTitle: '',
        ruleValue: '',
        ruleType: '',
        ruleMin: '',
        ruleMax: '',
        enable: 1,
        categoryId: '',
        psychologyName: '',
        price: ''
      },
      ruleForm: {
        psychologyTitleId: '',
        title: '',
        rulesValue: '',
        ruleSex: '',
        type: '',
        enable: 1
      },
      ageMarks: {
        3: '3岁',
        18: '18岁'
      },
      marks: {
        3: '3岁',
        25: '25岁'
      },
      ruleMarks: {
        4: '4分',
        10: '10分'
      },
      mentalCategory: {
        categoryName: '',
        categoryType: 1,
      },
      mentalCategoryList: [],
      mentalCategoryDialogTitle: '添加心理测试表类目',
      showMentalCategory: false,
      mentalCategoryTotal: 0,
      pageMentalList: [],
      rules: {
        psychologyTitle: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        degree: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        ageRuleRange: [
          { required: true, validator: validateRange, trigger: 'blur' }
        ],
        ageRange: [
          { required: true, validator: validateRange, trigger: 'blur' }
        ],
        rulesValue: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        scoreRange: [
          { required: true, validator: validateScore, trigger: 'blur' }
        ],
        psychologyTitleId: [
          { required: true, message: '请选择所属心理表', trigger: 'blur' }
        ],
        psychologicalrulesId: [
          { required: true, message: '请选择所属规则设置', trigger: 'blur' }
        ],
        min: [
          { required: true, message: '最小分数不能为空', trigger: 'blur' }
        ],
        max: [
          { required: true, validator: validateMax, trigger: 'blur' }
        ],
        mins: [
          { required: true, message: '最小分数不能为空', trigger: 'blur' }
        ],
        maxs: [
          { required: true, validator: validateAnswerMax, trigger: 'blur' }
        ],
        minage: [
          { required: true, message: '最小年龄不能为空', trigger: 'blur' }
        ],
        maxage: [
          { required: true, validator: validateAge, trigger: 'blur' }
        ],
        ruleSex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        psychologicalDesc: [
          { required: true, message: '简介不能为空', trigger: 'blur' }
        ],
        categoryName: [
          { required: true, message: '类目名称不能为空', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '所属类目不能为空', trigger: 'blur' }
        ],
        psychologyName: [
          { required: true, message: '创建人不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    clearSearch () {
      if (!this.searchTxt) {
        switch (this.name) {
          case '0':
            this.fetchMentalChartByPage(1);
            break
          case '1':
            this.fetchRuleList(1, null);
            break
          case '2':
            this.fetchAnswers(1, null);
            break
          case '3':
            this.fetchMentalCategoryList(1);
            break
          default:
            break
        }
      }
    },
    handleClick (tab,event){
      this.name = tab.name;
      switch (this.name) {
        case '0':
          this.placeText = '心理测试表';
          break
        case '1':
          this.placeText = '心理评测规则';
          break
        case '2':
          this.placeText = '心理评测答案';
          break
        case '3':
          this.placeText = '心理类目';
          break
        default:
          break
      }
    },
    handleSearch () { // 搜索事件
      if (!this.$checkAuth('canSearchTest')) {
        return this.$message.error('暂无对应操作权限!')
      };
      if (!this.searchTxt.trim()) {
        this.searchTxt = '';
        return this.$message.error('请输入搜索内容')
      };
      switch (this.name) {
        case '0':
          this.fetchMentalChartByPage(1, this.searchTxt);
          break
        case '1':
          this.fetchRuleList(1, this.searchTxt);
          break
        case '2':
          this.fetchAnswers(1, this.searchTxt);
          break
        case '3':
          this.fetchMentalCategoryList(1, this.searchTxt);
          break
        default:
          break
      }
    },
    fetchAllRules (title) { // 不分页查询心理规则
      getAllMentalRule({
        queryParam: {
          title:title
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          this.metalRules = res.data.data;
          console.log(this.metalRules)
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    chartChange (e) {
      let title = this.curMentalList.filter(item => item.psychologyTitleId === e)[0].psychologyTitle;
      let fitOne = this.metalRules.filter(item => item.psychologyTitle === title);
      this.answerRuleList = fitOne;
      this.mentalAnswer.psychologicalrulesId = ''
    },
    changeGender (e) {
      let list = this.curMentalList.filter(item => item.sex == e);
      this.answerChartList = list;
      this.mentalAnswer.psychologyTitleId = '';
      this.mentalAnswer.psychologicalrulesId = '';
      this.answerRuleList = []
    },
    changeRuleSex (e) {
      console.log(this.curMentalList);
      this.fitMentalList = this.curMentalList.filter(item => Number(item.sex) === e);
      // this.usefulQuestion = this.questions.filter(item => item.sex == e);
      this.ruleForm.rulesValue = '';
      this.ruleForm.psychologyTitleId = ''
    },
    fetchAnswers (index, psychologyTitle) { // 获取心理答案设置
      this.answerLoading = true;
      psychologyTitle = psychologyTitle || null;
      getMentalAnswer({
        index,
        count: this.pageSize,
        queryParam: {
          psychologyTitle: psychologyTitle
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list;
          this.answerTotal = res.data.data.totalRecord;
          list.forEach(item => {
            item.createDate = formatDate(item.createDate);
            item.isEnable = item.enable ? true : false
            // item.chartTitle = this.curMentalList.filter(m => m.psychologyTitleId === item.psychologyTitleId)[0].title;
            // item.ruleTitle = this.mentalRules.filter(m => m.psychologicalrulesId === item.psychologicalrulesId)[0].title
          });
          console.log(list)
          this.mentalAnswerList = list
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        };
        this.answerLoading = false
      })
      .catch(e => {
        this.answerLoading = false;
        this.$message.error('网络异常!')
      })
    },
    openAnswerEdit (row) { // 打开答案编辑输入框
      if (!this.$checkAuth('canEditAnswerSetting')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.curAnswerId = row.id;
      this.mentalAnswer.enable = row.enable;
      this.mentalAnswer.psychologyTitleId = row.psychologyTitleId;
      this.mentalAnswer.psychologicalrulesId = row.psychologicalrulesId;
      this.mentalAnswer.mins = row.mins;
      this.mentalAnswer.maxs = row.maxs;
      this.mentalAnswer.keywordId = row.keywordId;
      this.mentalAnswer.keywordTitle = row.keywordTitle;
      this.mentalAnswer.rulesValue = row.rulesValue;
      this.mentalAnswer.type = row.type ? Number(row.type) : '';
      this.mentalAnswer.minage = row.minage;
      this.mentalAnswer.maxage = row.maxage;
      this.mentalAnswer.sex = Number(row.sex);
      this.mentalAnswer.degree = row.degree;
      this.mentalAnswer.fractionType = Number(row.fractionType ? row.fractionType : 1);
      this.answerDialogTitle = '修改心理测评答案设置';
      this.showAnswerDialog = true
    },
    handleAnswerPagi (page) {
      this.curAnswerPage = page;
      this.fetchAnswers(page, this.searchTxt)
    },
    hideAnswerDialog () {
      this.showAnswerDialog = false
    },
    openAnswerAddDialog () {
      if (!this.$checkAuth('canAddAnswerSetting')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.mentalAnswer.minage = '';
      this.mentalAnswer.maxage = '';
      this.mentalAnswer.sex = '';
      this.mentalAnswer.psychologyTitleId = '';
      this.mentalAnswer.psychologicalrulesId = '';
      this.mentalAnswer.mins = '';
      this.mentalAnswer.maxs = '';
      this.mentalAnswer.rulesValue = '';
      this.mentalAnswer.type = '';
      this.mentalAnswer.degree = '';
      this.answerDialogTitle = '添加心理测评答案设置';
      this.showAnswerDialog = true
    },
    addAnswer (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.canUse = true;
          if (this.answerDialogTitle === '添加心理测评答案设置') {
            addMentalAnswer(this.mentalAnswer)
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                this.showAnswerDialog = false;
                this.fetchAnswers(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              };
              this.canUse = false
            })
            .catch(e => {
              this.canUse = false;
              this.$message.error('网络异常!')
            })
          } else {
            updateMentalAnswer({
              id: this.curAnswerId,
              ...this.mentalAnswer
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.showAnswerDialog = false;
                this.fetchAnswers(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              };
              this.canUse = false
            })
            .catch(e => {
              this.canUse = false;
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    deleteAnswer (row) { // 删除答案
      if (!this.$checkAuth('canDeleteAnswerSetting')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm('此操作将永久删除该答案设置, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMentalAnswer(row.id)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchAnswers(1)
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.$message.error('网络异常!')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    openRuleEdit (row) {
      if (!this.$checkAuth('canEditMentalRule')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.curRuleId = row.id;
      this.ruleForm.psychologyTitleId = row.psychologyTitleId;
      this.ruleForm.enable = row.enable;
      this.ruleForm.title = row.title;
      this.ruleForm.type = Number(row.type);
      this.ruleForm.rulesValue = JSON.parse(row.rulesValue);
      let sex = this.curMentalList.filter(item => item.psychologyTitleId == row.psychologyTitleId)[0].sex;
      this.fitMentalList = this.curMentalList.filter(item => item.sex == sex);
      this.ruleForm.ruleSex = Number(sex);
      this.ruleForm.ageRuleRange = [Number(row.minage), Number(row.maxage)];
      let tObj = {};
      tObj[Number(row.minage)] = Number(row.minage) + '岁';
      tObj[Number(row.maxage)] = Number(row.maxage) + '岁';
      this.ageMarks = tObj;
      this.ruleForm.min = row.mins;
      this.ruleForm.max = row.maxs;
      if (row.mins && row.maxs) {
        this.ruleForm.scoreRange = [Number(row.mins), Number(row.maxs)];
        let obj = {};
        obj[Number(row.mins)] = Number(row.mins) + '分';
        obj[Number(row.maxs)] = Number(row.maxs) + '分';
        this.ruleMarks = obj
      } else {
        this.ruleForm.scoreRange = [4, 10];
        this.ruleMarks = {
          4: '4分',
          10: '10分'
        }
      };
      this.ruleDialogTitle = '修改心理评测规则';
      this.showRuleDialog = true
    },
    sexFilter (gender) {
      let res = '';
      switch (gender) {
        case '1':
          res = '男';
          break
        case '2':
          res = '女';
          break
        case '3':
          res = '无性别限制';
          break
        default:
          break
      };
      return res
    },
    deleteRule (row) {
      if (!this.$checkAuth('canDeleteMentalRule')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMentalRule(row.id)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchRuleList(1)
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.$message.error('网络异常!')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    fetchAllMentals (psychologyTitle) { // 获取所有心理健康测试表(不分页)
      this.loading = true;
      psychologyTitle = psychologyTitle || null;
      getAllMentalChart({
        queryParam: {
          psychologyTitle: psychologyTitle,
        }
      })
      .then(res => {
        this.loading = false;
        if (res.data.code === 1) {
          let list = res.data.data;
          let len = list.length;
          for (let i = 0; i < len; i ++) {
            list[i].createDate = formatDate(list[i].createDate);
            list[i].isEnable = list[i].enable ? true : false
          };
          this.curMentalList = list;
          this.usefulChart = list;
          this.filterType = `全部(${list.length})`;
          this.types[0].total = list.filter(item => item.type == '0').length;
          this.types[1].total = list.filter(item => item.type == '1').length;
          this.types[2].total = list.filter(item => item.type == '2').length;
          this.types[3].total = list.filter(item => item.type == '3').length;
          // this.oldMentalList = list.filter(item => item.isCurrent === '0');
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.loading = false;
        this.$message.error('网络异常!')
      })
    },
    openRuleDialog () { // 打开规则设置弹出框
      if (!this.$checkAuth('canAddMentalRule')) {
        return this.$message.error('暂无对应操作权限!')
      };
      // this.ruleForm.psychologyTitleId = '';
      // this.ruleForm.title = '';
      // this.ruleForm.type = '';
      // this.ruleForm.rulesValue = '';
      // this.ruleMarks = {
      //   4: '4分',
      //   10: '10分'
      // };
      // this.ruleForm.scoreRange = [4, 10];
      // this.ruleForm.min = '';
      // this.ruleForm.max = '';
      this.ruleDialogTitle = '添加心理评测规则';
      this.showRuleDialog = true
    },
    changeRuleAgeRange () {
      let obj = {};
      obj[Number(this.ruleForm.ageRuleRange[0])] = Number(this.ruleForm.ageRuleRange[0]) + '岁';
      obj[Number(this.ruleForm.ageRuleRange[1])] = Number(this.ruleForm.ageRuleRange[1]) + '岁';
      this.ageMarks = obj
    },
    handlePagi (page) {
      this.curRulePage = page;
      this.fetchRuleList(page, this.searchTxt)
    },
    typeFilter (type) {
      let res = '';
      switch (type) {
        case '0':
          res = '除';
          break
        case '1':
          res = '乘';
          break
        case '2':
          res = '和';
          break;
        default:
          break
      };
      return res
    },
    hideRuleDialog () {
      this.showRuleDialog = false
    },
    fetchRuleList (index, title) { // 查询规则列表
      this.ruleLoading = true;
      title = title || null;
      getMentalRuleList({
        index,
        count: this.pageSize,
        queryParam: {
          title: title,
        }
      })
      .then(res => {
        this.ruleLoading = false;
        if (res.data.code === 1) {
          this.ruleTotal = res.data.data.totalRecord;
          let list = res.data.data.list;
          // console.log(list, this.curMentalList)
          list.forEach(item => {
            item.createDate = formatDate(item.createDate);
            item.chartTitle = item.psychologyTitleId;
            item.isEnable = item.enable ? true : false
          });
          this.mentalRules = list
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        console.log(e)
        this.ruleLoading = false;
        this.$message.error('网络异常!')
      })
    },
    addRule (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.isDoing = true;
          if (this.ruleDialogTitle === '添加心理评测规则') {
            addMentalRule({
              psychologyTitleId: this.ruleForm.psychologyTitleId,
              title: this.ruleForm.title,
              rulesValue: JSON.stringify(this.ruleForm.rulesValue),
              type: this.ruleForm.type
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                this.showRuleDialog = false;
                this.fetchRuleList(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              };
              this.isDoing = false
            })
            .catch(e => {
              this.isDoing = false;
              this.$message.error('网络异常!')
            })
          } else {
            updateMentalRule({
              id: this.curRuleId,
              psychologyTitleId: this.ruleForm.psychologyTitleId,
              title: this.ruleForm.title,
              rulesValue: JSON.stringify(this.ruleForm.rulesValue),
              type: this.ruleForm.type,
              enable: this.ruleForm.enable
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.showRuleDialog = false;
                this.fetchRuleList(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              };
              this.isDoing = false;
            })
            .catch(e => {
              this.isDoing = false;
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchQuestions () { // 查询所有心理题目
      getAllMentalQuestion()
      .then(res => {
        if (res.data.code === 1) {
          this.questions = res.data.data
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    seeDetail (row) { // 查看心理表详情
      if (!this.$checkAuth('canSeeMentalChartDetail')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$router.push('/test/mental/' + row.psychologyTitleId)
    },
    delMental ({ psychologyTitleId }) { // 删除心理表详情
      if (!this.$checkAuth('canDeleteMentalChart')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm('此操作将永久删除该表, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMentalChart(psychologyTitleId)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchMentalChartByPage(1, this.searchTxt)
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.$message.error('网络异常!')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    openAddDialog () {
      if (!this.$checkAuth('canAddMentalChart')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.mentalForm.psychologyTitle = '';
      this.mentalForm.type = '';
      this.mentalForm.sex = '';
      this.mentalForm.ageRange = [3, 25];
      this.mentalForm.psychologicalDesc = '';
      this.mentalForm.categoryId = '';
      this.mentalForm.psychologyName = '';
      this.mentalForm.price = '';
      this.marks = {
        3: '3岁',
        25: '25岁'
      };
      this.dialogTitle = '添加心理健康测试';
      this.showDialog = true
    },
    openEditDialog (row) {
      if (!this.$checkAuth('canEditMentalChart')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.mentalForm.psychologyTitle = row.psychologyTitle;
      this.mentalForm.type = Number(row.type);
      this.mentalForm.sex = Number(row.sex);
      this.mentalForm.ageRange = [Number(row.minage), Number(row.maxage)];
      this.mentalForm.psychologicalDesc = row.psychologicalDesc;
      this.mentalForm.enable = row.enable;
      this.mentalForm.categoryId = Number(row.categoryId);
      this.mentalForm.psychologyName = row.psychologyName;
      this.mentalForm.price = row.price;
      let obj = {};
      obj[Number(row.minage)] = row.minage + '岁';
      obj[Number(row.maxage)] = row.maxage + '岁';
      this.marks = obj;
      this.mentalForm.mentalId = row.psychologyTitleId;
      this.dialogTitle = '修改心理健康测试';
      this.showDialog = true
    },
    hideDialog () {
      this.showDialog = false
    },
    changeRange () {
      let obj = {};
      let range = this.mentalForm.ageRange;
      obj[range[0]] = range[0] + '岁';
      obj[range[1]] = range[1] + '岁';
      this.marks = obj
    },
    changeRuleRange () {
      let obj = {};
      let range = this.ruleForm.scoreRange;
      obj[range[0]] = range[0] + '分';
      obj[range[1]] = range[1] + '分';
      this.ruleMarks = obj
    },
    addMentalChart (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.dialogTitle === '添加心理健康测试') {
            addMental({
              psychologyTitle: this.mentalForm.psychologyTitle,
              psychologicalDesc: this.mentalForm.psychologicalDesc,
              type: this.mentalForm.type,
              minage: this.mentalForm.ageRange[0],
              maxage: this.mentalForm.ageRange[1],
              sex: this.mentalForm.sex,
              categoryId: this.mentalForm.categoryId,
              psychologyName: this.mentalForm.psychologyName,
              price: this.mentalForm.price || '00.00'
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                });
                this.showDialog = false;
                this.fetchMentalChartByPage(1, this.searchTxt)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          } else {
            editMental({
              psychologyTitleId: this.mentalForm.mentalId,
              psychologyTitle: this.mentalForm.psychologyTitle,
              psychologicalDesc: this.mentalForm.psychologicalDesc,
              type: this.mentalForm.type,
              minage: this.mentalForm.ageRange[0],
              maxage: this.mentalForm.ageRange[1],
              sex: this.mentalForm.sex,
              enable: this.mentalForm.enable,
              categoryId: this.mentalForm.categoryId,
              psychologyName: this.mentalForm.psychologyName,
              price: this.mentalForm.price || '00.00'
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                });
                this.showDialog = false;
                this.fetchMentalChartByPage(1, this.searchTxt)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    confirmChange (e, data, type) { // 确认启用/禁用
      this.$confirm(`确定${e ? '启用' : '禁用'}此${type}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        if (type === '测试表') {
          if (!this.$checkAuth('canSetMentalChartStatus')) {
            return this.$message.error('暂无对应操作权限!')
          };
          this.changeMentalStatus(data)
        } else if (type === '心理规则') {
          if (!this.$checkAuth('canSetMentalRuleStatus')) {
            return this.$message.error('暂无对应操作权限!')
          };
          this.changeRuleStatus(data)
        } else if (type === '心理答案') {
          if (!this.$checkAuth('canSetAnswerSettingStatus')) {
            return this.$message.error('暂无对应操作权限!')
          };
          this.changeAnswerStatus(data)
        }
      })
      .catch(err => {
        data.isEnable = !e;
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    changeMentalStatus (data) { // 修改心理状态
      editMental({
        psychologyTitleId: data.psychologyTitleId,
        psychologyTitle: data.psychologyTitle,
        psychologicalDesc: data.psychologicalDesc,
        type: data.type,
        minage: data.minage,
        maxage: data.maxage,
        sex: data.sex,
        enable: data.isEnable ? 1 : 0
      })
      .then(res => {
        if (res.data.code === 1) {
          this.$message({
            type: 'success',
            message: '操作成功'
          });
          this.fetchAllMentals()
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    changeRuleStatus (data) { // 修改规则状态
      updateMentalRule({
        id: data.id,
        psychologyTitleId: data.psychologyTitleId,
        title: data.title,
        rulesValue: data.rulesValue,
        type: data.type,
        enable: data.isEnable ? 1 : 0
      })
      .then(res => {
        if (res.data.code === 1) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.fetchRuleList(this.curRulePage)
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    changeAnswerStatus (data) { // 修改答案设置状态
      updateMentalAnswer({
        id: data.id,
        psychologyTitleId: data.psychologyTitleId,
        psychologicalrulesId: data.psychologicalrulesId,
        mins: data.mins,
        maxs: data.maxs,
        minage: data.minage,
        maxage: data.maxage,
        rulesValue: data.rulesValue,
        type: data.type,
        sex: data.sex,
        enable: data.isEnable ? 1 : 0
      })
      .then(res => {
        if (res.data.code === 1) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.fetchAnswers(this.curAnswerPage)
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    changeQuestion (e) { // 心理规则心理选择框change
      this.ruleForm.rulesValue = '';
      getQuestionListByMentalId(e)
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          this.usefulQuestion = list.filter(item => item)
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    fetchMentalCategoryList (index) { // 分页查询心理分类
      getMentalCategoryByPage({
        count: this.pageSize,
        index
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.mentalCategoryTotal = res.data.data.totalRecord;
          this.mentalCategoryList = list.map(item => {
            item.createDate = formatDate(item.createDate);
            return item
          })
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    hideCategoryDialog () { // 隐藏类目弹出框
      this.showMentalCategory = false
    },
    addCategory (name) { // 添加类目信息
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.mentalCategoryDialogTitle === '添加心理测试表类目') {
            addMentalCategory({
              categoryName: this.mentalCategory.categoryName,
              categoryType: this.mentalCategory.categoryType
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                this.showMentalCategory = false;
                this.fetchMentalCategoryList(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => [
              this.$message.error('服务异常!')
            ])
          } else {
            updateMentalCategory({
              categoryId: this.mentalCategory.categoryId,
              categoryName: this.mentalCategory.categoryName
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.showMentalCategory = false;
                this.fetchMentalCategoryList(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => [
              this.$message.error('服务异常!')
            ])
          }
        } else {
          return false
        }
      })
    },
    openAddCategoryDialog () { // 打开类目弹出框
      this.mentalCategoryDialogTitle = '添加心理测试表类目';
      this.mentalCategory.categoryName = '';
      this.showMentalCategory = true
    },
    openEditCategory (data) { // 修改心理类目
      this.mentalCategoryDialogTitle = '修改心理测试表类目';
      this.mentalCategory.categoryName = data.categoryName;
      this.mentalCategory.categoryId = data.categoryId;
      this.showMentalCategory = true
    },
    deleteCategory (data) {
      this.$confirm(`确定将心理类目: ${data.categoryName} 删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        deleteMentalCategory(data.categoryId)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            this.fetchMentalCategoryList(1)
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    handleCategoryPagi (page) { // 心理类目分页事件
      this.fetchMentalCategoryList(page, this.searchTxt)
    },
    fetchAllMentalCategory () { // 查询所有心理类目
      getAllMentalCategory()
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          this.allMentalCategory = list
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    changeChartType (e) { // 更改测试表类型
      // e = e.split('(')[0];
      // if (e === '全部') {
      //   this.usefulChart = this.curMentalList;
      //   return
      // };
      // let type = this.types.filter(item => item.label == e)[0].value;
      // this.usefulChart = this.curMentalList.filter(item => item.type == type)
    },
    fetchMentalChartByPage (index, title = null) { // 分页查询心理标题
      getMentalChartByPage({
        index,
        count: this.pageSize,
        queryParam: {
          psychologyTitle: title
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.mentalTotal = res.data.data.totalRecord || 0;
          let len = list.length;
          for (let i = 0; i < len; i ++) {
            list[i].createDate = formatDate(list[i].createDate);
            list[i].isEnable = list[i].enable ? true : false
          };
          this.pageMentalList = list
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    handleMentalPagi (page) { // 心理测试表分页
      this.curMentalPage = page;
      this.fetchMentalChartByPage(page, this.searchTxt)
    },
    fetchAllKeywords () { // 查询所有关键字
      getAllKeyWords()
      .then(res => {
        let list = res.data.data || [];
        this.keywordList = list;
        console.log(list)
      })
      .catch(e => {})
    },
    changeKeyword (e) { // 切换关键字
      this.mentalAnswer.keywordTitle = this.keywordList.find(item => item.keywordId == e).keywordTitle
    }
  },
  filters: {
    formatType (type) {
      type = Number(type);
      let res = '';
      switch (type) {
        case 0:
          res = '自测';
          break
        case 1:
          res = '他测';
          break
        case 2:
          res = '初筛表';
          break
        case 3:
          res = '基础量表';
          break
        case 6:
          res = '医生帮测量表';
          break
        default:
          res = '暂无类别';
          break
      };
      return res
    }
  },
  created () {
    this.fetchAllMentals();
    this.fetchQuestions();
    this.fetchAllRules();
    this.fetchRuleList(1);
    this.fetchAnswers(1);
    this.fetchAllKeywords();
    this.fetchMentalCategoryList(1);
    this.fetchAllMentalCategory();
    this.fetchMentalChartByPage(1)
  }
}
</script>
<style lang="scss">
  .age-slider {
    .el-slider__marks-text {
      white-space: nowrap!important;
    }
  }
  .metal-health {
    table {
      .cell {
        text-align: center;
      }
    }
    .chart-head {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  .metal-health {
    .search {
      display: flex;
    }
    table {
      .cell {
        text-align: center;
      }
    }
  }
  .search{}
</style>
